package com.lx.algorithm.Tree;


import java.util.LinkedList;
import java.util.Queue;

/**
 * Description:
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2021-10-17 18:18:20
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2021-10-17     张李鑫                     1.0         1.0 Version
 */
public class PrintLevel {

    static class Node<T> {
        T value;
        Node left;
        Node right;

        public Node(T value) {
            this.value = value;
        }
    }


    /**
     * <p>
     *    按层遍历
     *    用两个节点记录 当前层的最后一个节点 还有一个层的最后一个节点
     *    每次都判断当前层的节点是不是最后一个节点 如果是的话 把当前层的左右两个节点都加入到队列里面去
     *    然后重置 遍历完最后一层以后返回max
     * </p>
     * @param  node
     * @return int
     * @Author zlx
     * @date 2021/10/17
     */
    public static int printLevel(Node node) {
        if (node == null) {
            return 0;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.add(node);
        Node curEnd = node;
        Node nextEnd = null;
        int max = 0;
        int count = 0;
        while (!queue.isEmpty()) {
            Node poll = queue.poll();
            count++;


            if (poll.left!=null){
                queue.add(poll.left);
                nextEnd=poll.left;
            }

            if (poll.right!=null){
                queue.add(poll.right);
                nextEnd=poll.right;
            }

            if (poll==curEnd){
                max= Math.max(count, max);
                curEnd=nextEnd;
                count=0;
            }
        }
        return max;
    }
}